//
//  ZYCManagmentRecordViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/11.
//

#import "ZYCManagmentRecordViewController.h"
#import "ZYCAttendanceRecordMenuView.h"
#import "ZYCAttendanceStatusStatisticsView.h"
#import "ZYCAttendanceRecordModel.h"
#import "ZYCStuNotAttendanceRecordCell.h"
#import "ZYCStuAttendanceRecordCell.h"
#import "ZYCSelectPastDateView.h"
#import "ZYCCommonSelectObjectPickerView.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCStuAttendanceRecordCalendarViewController.h"
#import "UITableView+NoData.h"


static NSInteger pageSize = 10;

@interface ZYCManagmentRecordViewController ()<UITableViewDelegate,UITableViewDataSource,ZYCStuNotAttendanceRecordCellDelegate,ZYCAttendanceRecordMenuViewDelegate,ZYCCommonSelectObjectPickerViewDelegate>

@property (nonatomic, strong) ZYCAttendanceRecordMenuView *menuView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, copy) NSString *grade;
@property (nonatomic, strong) NSArray *classArr;
@property (nonatomic, strong) NSMutableArray *statusArr;
@property (nonatomic, strong) NSMutableArray *stateArr;

@property (nonatomic, copy) NSString *attendanceDate;
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *statusPickerView;
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *classPickerView;
@property (nonatomic, strong) ZYCCommonSelectObjectPickerView *modifyPickerView;
@property (nonatomic, strong) ZYCSelectPastDateView *dateSelectView;

@property (nonatomic, strong) ZYCAttendanceStatusStatisticsView *headerView;
//是否考勤(1-已考勤，2-未考勤)
@property (nonatomic, copy) NSString *isAttendance;//
@property (nonatomic, copy) NSString *classId;//班级ID
@property (nonatomic, strong) NSMutableArray *dataSource;

// 考勤状态
@property (nonatomic, copy) NSString *attendanceStatus;
// 请假时长
@property (nonatomic, copy) NSString *durationLeave;
// 考勤ID
@property (nonatomic, copy) NSString *attendanceId;


@end

@implementation ZYCManagmentRecordViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.type == ZYCStuAttendanceTypeRecord) {
        self.title = @"考勤记录";
    }else{
        self.title = @"考勤管理";
    }

    self.attendanceDate = [self getCurrentTime];
    self.menuView.leftStr = self.attendanceDate;
    
    ZYCCommonBaseModel *first = self.classArr.firstObject;
    self.menuView.middleStr = first.name;
    self.classId = first.nameId;
    
    ZYCCommonBaseModel *second  = self.statusArr.firstObject;
    self.isAttendance = second.nameId;
    self.menuView.rightStr = second.name;
    
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;

    [self loadNewData];
    [self loadStuAttendnceStatistics];
}
#pragma mark - 网络请求
// 统计数据(头部数据)
- (void)loadStuAttendnceStatistics{
    NSDictionary *params = @{
        @"attendanceDate":self.attendanceDate ? self.attendanceDate : @"",
        @"classId":self.classId ? self.classId : @"",
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AttendanceRecord requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.headerView.countZC = responseObject[@"body"][@"countZC"];
                self.headerView.countCD = responseObject[@"body"][@"countCD"];
                self.headerView.countQJ = responseObject[@"body"][@"countQJ"];
                self.headerView.countWD = responseObject[@"body"][@"countWD"];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

// 列表
- (void)loadNewData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"pageNum":@(self.pageNum),
        @"pageSize":@(pageSize),
        @"classId":self.classId ? self.classId : @"",
        @"isAttendance":self.isAttendance ? self.isAttendance : @"",
        @"attendanceDate": self.attendanceDate ? self.attendanceDate : @""
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AttendanceRecordTeacherList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCAttendanceRecordModel class] json:responseObject[@"body"][@"list"]];
                [self.dataSource addObjectsFromArray:array];
                [self.tableView showDataCount:self.dataSource.count];
                [self.tableView reloadData];
                [self reset];
                [self.tableView.mj_header endRefreshing];

            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_header endRefreshing];
        }];
}

-(void)loadMoreData{
    self.pageNum ++;
    NSDictionary *params = @{
        @"pageNum":@(self.pageNum),
        @"pageSize":@(pageSize),
        @"classId":self.classId ? self.classId : @"",
        @"isAttendance":self.isAttendance ? self.isAttendance : @"",
        @"attendanceDate": self.attendanceDate ? self.attendanceDate : @""
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AttendanceRecordTeacherList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCAttendanceRecordModel class] json:responseObject[@"body"][@"list"]];
                if (array.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.dataSource addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_footer endRefreshing];
        }];
}


- (void)reset{
    [self.tableView.mj_footer setRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_footer resetNoMoreData];
}

#pragma mark - ZYCAttendanceRecordMenuViewDelegate
// 时间
- (void)attendanceRecordMenuViewClickLeft{
    [self.dateSelectView show];
}
// 班级
- (void)attendanceRecordMenuViewClickMiddle{
    [self.classPickerView show];
}
//考勤状态
- (void)attendanceRecordMenuViewClickRight{
    [self.statusPickerView show];
}

#pragma mark - ZYCStuNotAttendanceRecordCellDelegate
- (void)studentNotAttendanceRecordCellDidModify:(ZYCAttendanceRecordModel *)model{
    self.attendanceId = model.attendanceId;
    [self.modifyPickerView show];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.isAttendance integerValue] == 1) {// 已考勤
        ZYCStuAttendanceRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCStuAttendanceRecordCell class]) forIndexPath:indexPath];
        cell.model = self.dataSource[indexPath.section];
        [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
        return cell;
    }else{// 未考勤
        ZYCStuNotAttendanceRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCStuNotAttendanceRecordCell class]) forIndexPath:indexPath];
        cell.model = self.dataSource[indexPath.section];
        cell.delegate = self;
        cell.type = self.type;
        [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
        return cell;
    }

}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.isAttendance integerValue] == 1) {//已考勤
        return 100.0f;
    }else{//未考勤
        return 55.0f;
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYCStuAttendanceRecordCalendarViewController *vc = [ZYCStuAttendanceRecordCalendarViewController new];
    ZYCAttendanceRecordModel *model = self.dataSource[indexPath.section];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ZYCCommonSelectObjectPickerViewDelegate
- (void)selectObjectPickerView:(ZYCCommonSelectObjectPickerView *)pickerView DidClickModel:(ZYCCommonBaseModel *)model{
    if (pickerView == self.classPickerView) {
        self.classId = model.nameId;
        self.menuView.middleStr = model.name;
        [self loadNewData];
        [self loadStuAttendnceStatistics];
    }else if(pickerView == self.statusPickerView){
        self.isAttendance = model.nameId;
        self.menuView.rightStr = model.name;
        [self loadNewData];
        [self loadStuAttendnceStatistics];
    }else if(pickerView == self.modifyPickerView){
        self.attendanceStatus = model.nameId;
        [self modifyState];
    }
}

- (void)modifyState{

    NSString *durationLeave = nil;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.attendanceId forKey:@"attendanceId"];
    [params setObject:self.attendanceDate forKey:@"attendanceDate"];
    
    if ([self.attendanceStatus integerValue] == 2) {//正常
        [params setObject:@"2" forKey:@"attendanceStatus"];
    }else if ([self.attendanceStatus integerValue] == 3) {//迟到
        [params  setObject:@"3" forKey:@"attendanceStatus"];
    }else if ([self.attendanceStatus integerValue] == 4) {//全天假
        durationLeave = @"3";
        [params  setObject:durationLeave forKey:@"durationLeave"];
        [params  setObject:@"4" forKey:@"attendanceStatus"];
    }else if([self.attendanceStatus integerValue] == 5){// 上午假
        durationLeave = @"1";
        [params  setObject:durationLeave forKey:@"durationLeave"];
        [params  setObject:@"4" forKey:@"attendanceStatus"];
    }else if([self.attendanceStatus integerValue] == 6){// 下午假
        durationLeave = @"2";
        [params  setObject:durationLeave forKey:@"durationLeave"];
        [params  setObject:@"4" forKey:@"attendanceStatus"];
    }

    [MrjSVProgressHUD showWithStatus:@"修改中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_UpdateAttendanceStatus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                [self loadStuAttendnceStatistics];
                [self loadNewData];
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

#pragma mark - getters

- (ZYCAttendanceStatusStatisticsView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCAttendanceStatusStatisticsView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    }
    return _headerView;
}

- (ZYCAttendanceRecordMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[ZYCAttendanceRecordMenuView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 46.0f)];
        _menuView.leftStr = @"日期";
        _menuView.middleStr = @"班级";
        _menuView.rightStr = @"考勤状态";
        _menuView.delegate = self;
    }
    return _menuView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.menuView.frame)) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCStuAttendanceRecordCell class] forCellReuseIdentifier:NSStringFromClass([ZYCStuAttendanceRecordCell class])];
        [_tableView registerClass:[ZYCStuNotAttendanceRecordCell class] forCellReuseIdentifier:NSStringFromClass([ZYCStuNotAttendanceRecordCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        // 设置了底部inset
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
        // 忽略掉底部inset
        _tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;
    }
    return _tableView;
}

// 时间选择器
- (ZYCSelectPastDateView *)dateSelectView {
    ZYCWeakSelf
    if (!_dateSelectView) {
        _dateSelectView = [[ZYCSelectPastDateView alloc] init];
        _dateSelectView.tipString = @"请选择时间";
        _dateSelectView.currentDate = [NSDate date];
        _dateSelectView.confirmAction = ^(NSString * _Nonnull dateStr) {
            weakSelf.menuView.leftStr = dateStr;
            weakSelf.attendanceDate = dateStr;
            [weakSelf loadNewData];
            [weakSelf loadStuAttendnceStatistics];
        };
        [self.view addSubview:_dateSelectView];
    }
    return _dateSelectView;
}
// 班级选择器
- (ZYCCommonSelectObjectPickerView *)classPickerView {
    if (!_classPickerView) {
        _classPickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _classPickerView.tipString = @"请选择班级";
        _classPickerView.dataSource = self.classArr;
        _classPickerView.delegate = self;
        [self.view addSubview:_classPickerView];
    }
    return _classPickerView;
}
// 考勤状态选择器
- (ZYCCommonSelectObjectPickerView *)statusPickerView {
    if (!_statusPickerView) {
        _statusPickerView = [[ZYCCommonSelectObjectPickerView alloc] init];
        _statusPickerView.tipString = @"请选择状态";
        _statusPickerView.dataSource = self.statusArr.copy;
        _statusPickerView.delegate = self;
        [self.view addSubview:_statusPickerView];
    }
    return _statusPickerView;
}
// 修改状态选择器
- (ZYCCommonSelectObjectPickerView *)modifyPickerView{
    if (!_modifyPickerView) {
        _modifyPickerView = [[ZYCCommonSelectObjectPickerView alloc]init];
        _modifyPickerView.tipString = @"请选择考勤状态";
        _modifyPickerView.dataSource = self.stateArr.copy;
        _modifyPickerView.delegate = self;
        [self.view addSubview:_modifyPickerView];
    }
    return _modifyPickerView;
}

- (NSMutableArray *)stateArr {
    if (!_stateArr) {
        NSMutableArray *temp = [NSMutableArray array];
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"正常";
            model.nameId = @"2";
            [temp addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"迟到";
            model.nameId = @"3";
            [temp addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"请假(全天假)";
            model.nameId = @"4";
            [temp addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"请假(上午假)";
            model.nameId = @"5";
            [temp addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"请假(下午假)";
            model.nameId = @"6";
            [temp addObject:model];
        }
        _stateArr = temp;
    }
    return _stateArr;
}



- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

- (NSMutableArray *)statusArr {
    if (!_statusArr) {
        NSMutableArray *temp = [NSMutableArray array];
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"已考勤";
            model.nameId = @"1";
            [temp addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [[ZYCCommonBaseModel alloc] init];
            model.name = @"未考勤";
            model.nameId = @"2";
            [temp addObject:model];
        }
        _statusArr = temp;
    }
    return _statusArr;
}

- (NSArray *)classArr {
    if (!_classArr) {
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [documentPath stringByAppendingPathComponent:@"class.data"];;
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        _classArr = array;
    }
    return _classArr;
}


- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
